package com.wzdigit.wms.basic.service.code.back;

import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.wzdigit.mes.basic.dto.StaffDTO;
import com.wzdigit.wms.basic.domain.dtos.mid.IfPostbackDto;
import com.wzdigit.wms.basic.enums.writeback.BackIsErrorRemindEnum;
import com.wzdigit.wms.basic.enums.writeback.BackResultEnum;
import com.wzdigit.wms.basic.mapper.core.mid.IfPostbackMapper;
import com.wzdigit.wms.basic.service.code.IMailCoreService;
import com.wzdigit.wms.basic.util.DateUtils;
import com.wzdigit.wms.basic.util.common.CommonString;
import lombok.extern.slf4j.Slf4j;

/**
 * WMS数据回传异常提醒【逻辑处理】
 * 
 * @author Administrator
 *
 */
@Service
@Slf4j
public class BackErrorRemindDealService {
	
	@Autowired
	private IfPostbackMapper ifPostbackMapper;
	
	@Autowired
	private IMailCoreService iMailCoreService;

	private static final String SUBJECT_TEXT = "WMS数据回传异常提醒";
	
	@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
	public void deal(IfPostbackDto backFailDto, List<StaffDTO> staffDTOList) throws Exception {
		StringBuilder baseContent = new StringBuilder();
		baseContent.append("<P style='text-indent:2em;'>你好，以下回传异常已经发生，请及时关注！")
			.append("<p>目标系统：").append(backFailDto.getDestSystem()).append("</p>")
			.append("<p>回传主题：").append(backFailDto.getPostbackTopic()).append("</p>")
			.append("<p>回传结果：").append(BackResultEnum.getEnumByCode(backFailDto.getPostbackResult()).enumName).append("</p>")
			.append("<p>回传单号：").append(backFailDto.getPostbackNo()).append("</p>")
			.append("<p>异常提醒时间：").append(DateUtils.format(new Date(), DateUtils.FORMATTEXT05)).append("</p>")
			.append("<P style='text-align:right;'>本消息发自WMS系统，请勿回复</P>");
		
		boolean isRemind = false;
		for (StaffDTO staffDTO : staffDTOList) {
			StringBuilder content = new StringBuilder();
			content.append("<P>").append(staffDTO.getStaffName()).append(":</P>").append(baseContent.toString());
			iMailCoreService.sendHtmlMail(staffDTO.getEmail(), SUBJECT_TEXT, content.toString());
			isRemind = true;
		}
		if(isRemind) {
			log.info("[WMS数据回传异常提醒]成功，回传ID[{}]", backFailDto.getIfPostbackId());
			ifPostbackMapper.updateIsErrorRemind(BackIsErrorRemindEnum.REMINDED.code, CommonString.DEFAULT_USER_NAME, backFailDto.getIfPostbackId());
		}
	}
}
